//
//  BacketballListViewController.m
//  movement
//
//  Created by lanou on 16/5/5.
//  Copyright © 2016年 lanou. All rights reserved.
//

#define kBacketballListURL @"http://c.3g.163.com/nc/article/list/T1348649145984/0-100.html"

#import "BacketballListViewController.h"
#import <AFNetworking.h>
#import "BacketballListModel.h"
#import "BaseTableViewCell.h"
#import "TableViewCellFactory.h"
#import "carouselView.h"
#import "NetworkRequest.h"
#import <MJRefresh.h>
#import "BallDetailsViewController.h"
#import "NBALiveViewController.h"
#import "NBATeamViewController.h"

@interface BacketballListViewController ()<UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *DataArr;
@property (nonatomic, strong) NSMutableArray *modelArr;
@property (nonatomic, strong) UIView *views;
@property (nonatomic, strong) NSDictionary *dict;
@end

@implementation BacketballListViewController
// 懒加载
- (NSDictionary *)dict {
    if (_dict == nil) {
        _dict = [NSDictionary dictionary];
    }
    return _dict;
}

- (NSMutableArray *)modelArr {
    if (_modelArr == nil) {
        _modelArr = [NSMutableArray array];
    }
    return _modelArr;
}

- (NSMutableArray *)DataArr {
    if (_DataArr == nil) {
        _DataArr = [NSMutableArray array];
    }
    return _DataArr;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor colorWithRed:0.746 green:0.687 blue:1.000 alpha:1.000];
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64 + 150 + 20, self.view.frame.size.width, self.view.frame.size.height - 64 - 170)];
    [self.tableView registerNib:[UINib nibWithNibName:@"BacketballListTableViewCell" bundle:nil] forCellReuseIdentifier:NSStringFromClass([BacketballListModel class])];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    [self.view addSubview:self.tableView];
    // 添加导航栏按钮
    UIBarButtonItem *live = [[UIBarButtonItem alloc] initWithTitle:@"赛事" style:(UIBarButtonItemStylePlain) target:self action:@selector(liveBlick)];
    UIBarButtonItem *team = [[UIBarButtonItem alloc] initWithTitle:@"球队资料" style:(UIBarButtonItemStylePlain) target:self action:@selector(teamBlick)];
    self.navigationItem.rightBarButtonItems = @[live, team];
    self.automaticallyAdjustsScrollViewInsets = NO;
    // 调用数据解析
    [self getData];
    // 下拉刷新
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self getData];
    }];
    // 上拉加载
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        [self loadData];
    }];
    [self loadViewTime];
    
}
// 加载等待
- (void)loadViewTime {
    self.views = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
    self.views.backgroundColor = [UIColor grayColor];
    [self.view addSubview:self.views];
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(self.view.frame.size.width / 2 - 30, self.view.frame.size.height / 2 - 30, 100, 30)];
    label.text = @"加载中";
    [self.views addSubview:label];
    UIImageView *gifImageView = [[UIImageView alloc] initWithFrame:CGRectMake(self.view.frame.size.width / 2 - 50, self.view.frame.size.height / 2, 100, 100)];
    NSMutableArray *gifArray = [NSMutableArray array];
    for (int i = 1; i < 9; i++) {
        [gifArray addObject:[UIImage imageNamed:[NSString stringWithFormat:@"c22c94c9cae12087c99ea404c664daba－%d（被拖移）.tiff",i]]];
    }
    gifImageView.animationImages = gifArray; //动画图片数组
    gifImageView.animationDuration = 2; //执行一次完整动画所需的时长
    gifImageView.animationRepeatCount = 100000000;  //动画重复次数
    [gifImageView startAnimating];
    [self.views addSubview:gifImageView];
}
// barButton点击事件
- (void)liveBlick {
    NBALiveViewController *nbaVC = [[NBALiveViewController alloc] init];
    [self.navigationController pushViewController:nbaVC animated:YES];
}
- (void)teamBlick {
    NBATeamViewController *nbaVC = [[NBATeamViewController alloc] init];
    [self.navigationController pushViewController:nbaVC animated:YES];
}
// 上拉加载
- (void)loadData {
    for (int i = 0; i < 20; i++) {
        [self.modelArr addObject:self.DataArr[i + 23]];
        [self.tableView reloadData];
        [self.tableView.mj_footer endRefreshing];
    }
}

// 数据解析
- (void)getData {
//    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
//    [manager GET:kBacketballListURL parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
    [NetworkRequest getUrl:kBacketballListURL CallBack:^(id data) {
        NSLog(@"11");
        self.dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves error:nil];
        NSArray *arr = [NSArray array];
        arr = self.dict[@"T1348649145984"];
        [self.modelArr removeAllObjects];
        [self.DataArr removeAllObjects];
        for (NSDictionary *dic in arr) {
            [self.DataArr addObject:[BacketballListModel modelWithDic:dic]];
        }
        for (int i = 0; i < 23; i++) {
            [self.modelArr addObject:self.DataArr[i]];
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            // 调用轮播图
            [self setCarouselView];
            [self.tableView reloadData];
            // 隐藏view
            self.views.hidden = YES;
            // 结束下拉刷新
            [self.tableView.mj_header endRefreshing];
        });
        
//    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//        NSLog(@"%@",error);
    }];
}

// 轮播图设置
- (void)setCarouselView{
    
    NSMutableArray *imagesArr = @[].mutableCopy;
    NSMutableArray *textArr = @[].mutableCopy;
    for (int i = 0; i < 3; i++) {
        BacketballListModel *model = self.modelArr[i];
        [imagesArr addObject:model.imgsrc];
        [textArr addObject:model.title];
    }
    carouselView *carView = [[carouselView alloc] initWithFrame:CGRectMake(0, 74, self.view.frame.size.width, 150) imageUrls:imagesArr textArr:textArr];
    [self.view addSubview:carView];
    
    // 轮播图点击
    carView.imageClick = ^(NSInteger index) {
        BallDetailsViewController *detailsVC = [[BallDetailsViewController alloc] init];
        BacketballListModel *model = self.modelArr[index];
        detailsVC.url = model.url;
        [self.navigationController pushViewController:detailsVC animated:YES];
    };
}

#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 130;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.modelArr.count - 3;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    BaseTableViewCell *cell = [TableViewCellFactory cellWithModelClass:[BacketballListModel class] tableView:tableView index:indexPath];
    BacketballListModel *model = self.modelArr[indexPath.row + 3];
    [cell setDataWithModel:model];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    BallDetailsViewController *detailsVC = [[BallDetailsViewController alloc] init];
    BacketballListModel *model = self.modelArr[indexPath.row + 3];
    detailsVC.url = model.url;
    [self.navigationController pushViewController:detailsVC animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
